package com.tao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tao.config.MyLog;
import com.tao.pojo.Address;
import com.tao.pojo.vo.ResponseResult;
import com.tao.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/address")
public class CmsAddressController {
    @Autowired
    private AddressService addressService;

    @MyLog("地址列表")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/list")
    public Object list(@RequestBody Address  address){
        LambdaQueryWrapper<Address> lqw = new LambdaQueryWrapper<>();
        lqw.eq(!ObjectUtils.isEmpty(address.getTitle()),Address::getTitle,address.getTitle());
        List<Address> list = addressService.list(lqw);
        return ResponseResult.success(list);
    }

    @MyLog("地址新增")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/add")
    public Object add(@RequestBody Address address){
        addressService.save(address);
        return ResponseResult.success(null);
    }

    @MyLog("地址修改")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/update")
    public Object update(@RequestBody Address address){
        LambdaQueryWrapper<Address> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Address::getId,address.getId());
        List<Address> list = addressService.list(lqw);
        if (list.size() == 0){
            return ResponseResult.error("地址不存在！");
        }
        addressService.updateById(address);
        return ResponseResult.success(null);
    }

    @MyLog("地址删除(注意判断id是否绑定其他数据)")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/remove")
    public Object remove(@RequestBody Address address){
        addressService.removeById(address.getId());
        return ResponseResult.success(null);
    }
}
